package com.aaa.common.util;

import ch.qos.logback.core.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.swing.*;
import java.util.concurrent.TimeUnit;

/**
 * fileName:ClusterRedisLock
 * description:通用的分布式锁工具类
 * author: Mr.Ge
 * createTime:2020/12/21 8:41
 * version:1.0.0
 */
@Component  //交给soring管理
public class ClusterRedisLock {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 加锁方法
     * @param key
     * @param second
     * @return
     */
    public boolean lock(String key,int second){
        //setnx(key,value) 不存在时设置值  expire(key,6000) 设置过期时间 delete(key)业务执行完成删除
        return redisTemplate.opsForValue().setIfAbsent(key,"clusterLock",second,TimeUnit.SECONDS);
    }

    /**
     * 解锁 业务执行完成删除锁
     * @param key
     * @return
     */
    public boolean unLock(String key){
    return redisTemplate.delete(key);
    }

}
